package com.smart.campus.web.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.smart.campus.school.domain.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

public class PdfUtil {
    /**
     * 创建pdf
     * @param examPaper
     * @param outputStream
     * @return
     */
    public static String createPdf(OutputStream outputStream, ExamPaper examPaper){
        //Map<String, Object> exam = JSONObject.parseObject(examjson, new TypeReference<Map<String, Object>>() { });
        try{
            //创建文件
            Document document = new Document(PageSize.A4.rotate());
            //设置字体
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //创建PDF
            PdfWriter writer =  PdfWriter.getInstance(document, outputStream);
            // 设置页面布局
            writer.setViewerPreferences(PdfWriter.PageLayoutOneColumn);
            // 页码
            writer.setPageEvent(new PageXofYTest());
            //打开文件
            document.open();

            //标题
            Paragraph paragraph = new Paragraph(150);//段落的间距
            //1 2 3  中右左
            paragraph.setAlignment(2);  //对齐方式
            Font font = new Font(bfChinese);//字体
            font.setSize(22);//字体大小
            paragraph.setFont(font);//设置段落字体
            Chunk chunk = new Chunk(examPaper.getName());
            paragraph.add(chunk);
            document.add(paragraph);

            Paragraph paragraph1 = new Paragraph(40);
            //1 2 3  中右左
            paragraph1.setAlignment(1);  //对齐方式
            Font font1 = new Font(bfChinese);//字体
            font1.setSize(20);
            paragraph1.setFont(font1);
            Chunk chunk1 = new Chunk(examPaper.getDescription());
            paragraph1.add(chunk1);
            //paragraph1.setSpacingBefore(-15);
            //paragraph1.setSpacingAfter(-50);//往下距离200
            document.add(paragraph1);

            //点线
            DottedLineSeparator line = new DottedLineSeparator();
            //下移5个单位
            line.setOffset(-15);
            //设置点之间的距离
            //line.setGap(20);
            document.add(line);

            //生成题目
            List<ExamQuestion> questionList = examPaper.getQuestionList();
            for (ExamQuestion question : questionList) {
                Paragraph questionPra = new Paragraph(150);
                //1 2 3  中右左
                questionPra.setAlignment(1);  //对齐方式
                questionPra.setFont(font1);
                Chunk questionChunk = new Chunk(question.getContent());
                questionPra.add(questionChunk);
                questionPra.setSpacingAfter(5);
                document.add(questionPra);
                //生成答案
                List<ExamAnswer> answerList = question.getAnswerList();
                for (ExamAnswer examAnswer : answerList) {
                    Paragraph answerPra = new Paragraph(150);
                    //1 2 3  中右左
                    answerPra.setAlignment(1);  //对齐方式
                    answerPra.setFont(font1);
                    Chunk answerChunk = new Chunk(examAnswer.getContent());
                    answerPra.add(answerChunk);
                    answerPra.setSpacingAfter(5);
                    document.add(answerPra);
                }
            }



            Paragraph paragraph3 = new Paragraph(150);
            //1 2 3  中右左
            paragraph3.setAlignment(1);  //对齐方式
            Font font3 = new Font(bfChinese);//字体
            font3.setSize(12);
            paragraph3.setFont(font3);
            Chunk chunk3 = new Chunk("编号："+getRandom(17));
            paragraph3.add(chunk3);
            paragraph3.setSpacingAfter(5);
            document.add(paragraph3);

            Paragraph paragraph4 = new Paragraph(15);
            //1 2 3  中右左
            paragraph4.setAlignment(1);  //对齐方式
            Font font4 = new Font(bfChinese);//字体
            font4.setSize(12);
            paragraph4.setFont(font4);
            SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
            Chunk chunk4 = new Chunk("文档生成日期："+df.format(System.currentTimeMillis()));
            paragraph4.add(chunk4);
            paragraph4.setSpacingAfter(5);
            document.add(paragraph4);

            document.newPage(); //换页

         /*   Paragraph answerPar = new Paragraph(20);				//标准答案
            answerPar.setAlignment(3);  //对齐方式
            Font answerfont = new Font(bfChinese);//字体
            answerfont.setSize(12);
            answerPar.setFont(answerfont);
            answerPar.add(answerchunk);
            answerPar.setSpacingAfter(5);
            document.add(answerPar);*/
            //关闭文档
            document.close();
            //关闭书写器
            writer.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        //ZIPUtil.compress(examPath,path+"/exam-"+paperid+".zip" );		//压缩
        return "ok";
    }
    /**
     * 生成指定位数的随机数
     * @param length
     * @return
     */
    public static String getRandom(int length){
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }

    /**
     *  生成考成座位表
     * @param examRoomSchedule 考场信息
     * @param path 文件路径
     * @return 返回文件名
     */
    public static String createExamSitesPdf(final ExamRoomSchedule examRoomSchedule,final String path){
        String fname = null;
        try{
            //创建文件
            Document document = new Document(PageSize.A4);
            //设置字体
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //创建PDF
            fname = path + System.currentTimeMillis()+".pdf";
            PdfWriter writer =  PdfWriter.getInstance(document, new FileOutputStream(new File(fname)));
            document.open();
            for(ExamRoomClasses room:examRoomSchedule.getList()){
                document.newPage();
                if(room.getStudentsList()!=null&&room.getStudentsList().size()>0){
                    getExamScheduleTitle(document, bfChinese, examRoomSchedule.getName(),room);
                    PdfPTable table = getRoomSitesTable(bfChinese, room);
                    document.add(table);
                    document.newPage();
                }
            }
            if(examRoomSchedule.getList()==null||examRoomSchedule.getList().size()==0){
                document.newPage();
            }

            //关闭文档
            document.close();
            //关闭书写器
            writer.close();


        }catch (Exception e){
            e.printStackTrace();
        }
        return fname;
    }

    private static PdfPTable getRoomSitesTable(BaseFont bfChinese, ExamRoomClasses room) throws DocumentException {
        PdfPTable table = new PdfPTable(6);
        int[] widths = {15,30,30,15,30,30};
        table.setWidths(widths);

        //设置控制
        table.setSpacingBefore(40);//表格前间距
        table.setSpacingAfter(100);//表格后间距
        table.setWidthPercentage(80);//表格宽占page比例
        table.setHorizontalAlignment(Element.ALIGN_CENTER);//表格水平对齐方式
        table.setHeaderRows(1);
        table.setPaddingTop(10f);//设置表格顶部padding
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);//单元格中文字垂直对齐方式
        table.getDefaultCell().setBorderColor(BaseColor.BLACK);//单元格线条颜色
        table.getDefaultCell().setMinimumHeight(40);//单元格最小高度
        table.getDefaultCell().setExtraParagraphSpace(8);//段落文字与表格之间的距离,底部距离
        table.getDefaultCell().setLeading(18, 0);//设置行间距
        Font f = new Font(bfChinese,12,Font.BOLD);
        Font f1 = new Font(bfChinese);
        Paragraph pst = new Paragraph("座位号", f);
        pst.setAlignment(1);
        PdfPCell h0 = new PdfPCell(pst);
        Paragraph psno = new Paragraph("学号", f);
        psno.setAlignment(1);
        Paragraph psname = new Paragraph("姓名", f);
        psname.setAlignment(1);
        PdfPCell h1 = new PdfPCell(psno);
        PdfPCell h2 = new PdfPCell(psname);
        table.addCell(h0);
        table.addCell(h1);
        table.addCell(h2);
        table.addCell(h0);
        table.addCell(h1);
        table.addCell(h2);
        int total = room.getStudentsList().size();
        int k0 = total/2;
        int yk = total%2;
        if(yk>0)
            k0+=1;
        for(int i = 0;i<k0;i++){
            ExamRoomStudents students = room.getStudentsList().get(i);
            PdfPCell h01 = new PdfPCell(new Phrase(students.getSiteNo(),f1));
            PdfPCell h02 = new PdfPCell(new Phrase(students.getStudentNo(),f1));
            PdfPCell h03 = new PdfPCell(new Phrase(students.getStudentName(),f1));
            table.addCell(h01);
            table.addCell(h02);
            table.addCell(h03);
            int k = i+k0;
            if(total>k){
                ExamRoomStudents students1 = room.getStudentsList().get(k);
                h01 = new PdfPCell(new Phrase(students1.getSiteNo(),f1));
                h02 = new PdfPCell(new Phrase(students1.getStudentNo(),f1));
                h03 = new PdfPCell(new Phrase(students1.getStudentName(),f1));
                table.addCell(h01);
                table.addCell(h02);
                table.addCell(h03);
            }else{
                h01 = new PdfPCell(new Phrase("",f1));
                table.addCell(h01);
                table.addCell(h01);
                table.addCell(h01);
            }
        }
        return table;
    }

    private static void getExamScheduleTitle(Document document, BaseFont bfChinese, String name,ExamRoomClasses room) throws DocumentException {
        //标题
        Paragraph paragraph = new Paragraph(5);//段落的间距
        //1 2 3  中右左
        paragraph.setAlignment(1);  //对齐方式
        Font font = new Font(bfChinese);//字体
        font.setSize(22);//字体大小
        paragraph.setFont(font);//设置段落字体
        Chunk chunk = new Chunk(name);
        paragraph.add(chunk);
        document.add(paragraph);
        Paragraph paragraph1 = new Paragraph(40);
        //1 2 3  中右左
        paragraph1.setAlignment(1);  //对齐方式
        Font font1 = new Font(bfChinese);//字体
        font1.setSize(20);
        paragraph1.setFont(font1);
        Chunk chunk1 = new Chunk(room.getRoomId()+"    "+(room.getLocation()==null?"":room.getLocation()));
        paragraph1.add(chunk1);
        //paragraph1.setSpacingBefore(-15);
        //paragraph1.setSpacingAfter(-50);//往下距离200
        document.add(paragraph1);

    }

    private static void getCourseScheduleTitle(Document document, BaseFont bfChinese, String name) throws DocumentException {
        //标题
        Paragraph paragraph = new Paragraph(5);//段落的间距
        //1 2 3  中右左
        paragraph.setAlignment(1);  //对齐方式
        Font font = new Font(bfChinese);//字体
        font.setSize(22);//字体大小
        paragraph.setFont(font);//设置段落字体
        Chunk chunk = new Chunk(name);
        paragraph.add(chunk);
        document.add(paragraph);
    }

    private static void getCourseWeekTitle(Document document, BaseFont bfChinese, String name) throws DocumentException {

        Paragraph paragraph1 = new Paragraph(20);
        //1 2 3  中右左
        paragraph1.setAlignment(1);  //对齐方式
        Font font1 = new Font(bfChinese);//字体
        font1.setSize(12);
        paragraph1.setFont(font1);
        Chunk chunk1 = new Chunk(name);
        paragraph1.add(chunk1);
        paragraph1.setPaddingTop(40);
        document.add(paragraph1);
    }

    public static String createCourseSchedulePdf(final JSONArray list, final String temp) {
        String fullName = temp+"/"+System.currentTimeMillis()+".pdf";
        try{
            Document document = new Document(PageSize.A4);
            //设置字体
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //创建PDF
            PdfWriter writer =  PdfWriter.getInstance(document, new FileOutputStream(new File(fullName)));
            document.open();
            document.newPage();
            JSONObject j = list.getJSONObject(0);
            getCourseScheduleTitle(document,bfChinese,j.getString("name"));
            for(int i=0;i<list.size();i++){
                JSONObject j0 = list.getJSONObject(i);
                getCourseWeekTitle(document,bfChinese, j0.getString("scheduleName")+"--"+j0.getString("typeName"));
                PdfPTable table = getWeekTable(bfChinese, j0);
                document.add(table);
            }
            //关闭文档
            document.close();
            //关闭书写器
            writer.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return  fullName;
    }

    public static String createCourseSchedulePdf(final JSONArray list, final OutputStream outputStream) {
        try{
            Document document = new Document(PageSize.A4);
            //设置字体
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //创建PDF
            PdfWriter writer =  PdfWriter.getInstance(document, outputStream);
            document.open();
            document.newPage();
            JSONObject j = list.getJSONObject(0);
            getCourseScheduleTitle(document,bfChinese,j.getString("name"));
            for(int i=0;i<list.size();i++){
                JSONObject j0 = list.getJSONObject(i);
                getCourseWeekTitle(document,bfChinese, j0.getString("scheduleName")+"--"+j0.getString("typeName"));
                PdfPTable table = getWeekTable(bfChinese, j0);
                document.add(table);
            }
            //关闭文档
            document.close();
            //关闭书写器
            writer.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return  "ok";
    }


    private static PdfPTable getWeekTable(BaseFont bfChinese, JSONObject week) throws DocumentException {
        int[] widths = {20,30,30,30,30,30,30,30};
        PdfPTable table = new PdfPTable(widths.length);
        table.setWidths(widths);
        //设置控制
        table.setSpacingBefore(5);//表格前间距
        table.setSpacingAfter(5);//表格后间距
        table.setWidthPercentage(90);//表格宽占page比例
        table.setHorizontalAlignment(Element.ALIGN_CENTER);//表格水平对齐方式
        table.setHeaderRows(1);
        table.setPaddingTop(5f);//设置表格顶部padding
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);//单元格中文字垂直对齐方式
        table.getDefaultCell().setBorderColor(BaseColor.BLACK);//单元格线条颜色
        table.getDefaultCell().setMinimumHeight(40);//单元格最小高度
        table.getDefaultCell().setExtraParagraphSpace(8);//段落文字与表格之间的距离,底部距离
        table.getDefaultCell().setLeading(14, 0);//设置行间距
        Font f = new Font(bfChinese,10,Font.BOLD);
        Font f1 = new Font(bfChinese);
        //设置表头
        String[] headers = {"节次","星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
        String[] headersKey = {"section","w1","w2","w3","w4","w5","w6","w7"};
        for(int i=0;i<headers.length;i++){
            Paragraph hi = new Paragraph(headers[i],f);
            hi.setAlignment(1);
            PdfPCell w1 = new PdfPCell(hi);
            w1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            table.addCell(w1);
        }

        List<JSONObject> list = (List<JSONObject>) week.get("list");
        for(int i = 0;i<list.size();i++){
            JSONObject j1 = list.get(i);
            for(int m=0;m<headersKey.length;m++){
                PdfPCell h01 = new PdfPCell(new Phrase(j1.getString(headersKey[m]),f1));
                h01.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                table.addCell(h01);
            }
        }
        return table;
    }

    //页码事件
    private static class PageXofYTest extends PdfPageEventHelper {
        public PdfTemplate total;

        public BaseFont bfChinese;

        /**
         * 重写PdfPageEventHelper中的onOpenDocument方法
         */
        @Override
        public void onOpenDocument(PdfWriter writer, Document document) {
            // 得到文档的内容并为该内容新建一个模板
            total = writer.getDirectContent().createTemplate(500, 500);
            try {

                String prefixFont = "";
                String os = System.getProperties().getProperty("os.name");
                if(os.startsWith("win") || os.startsWith("Win")){
                    prefixFont = "C:\\Windows\\Fonts" + File.separator;
                }else {
                    prefixFont = "/usr/share/fonts/chinese" + File.separator;
                }

                // 设置字体对象为Windows系统默认的字体
                //bfChinese = BaseFont.createFont(prefixFont + "simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            } catch (Exception e) {
                throw new ExceptionConverter(e);
            }
        }

        /**
         * 重写PdfPageEventHelper中的onEndPage方法
         */
        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            // 新建获得用户页面文本和图片内容位置的对象
            PdfContentByte pdfContentByte = writer.getDirectContent();
            // 保存图形状态
            pdfContentByte.saveState();
            String text ="www.rkpass.cn   "+ writer.getPageNumber();
            // 获取点字符串的宽度
            float textSize = bfChinese.getWidthPoint(text, 15);
            pdfContentByte.beginText();
            // 设置随后的文本内容写作的字体和字号
            pdfContentByte.setFontAndSize(bfChinese, 15);

            // 定位'X/'
            //System.out.println(document.right() +"...."+ document.left());
            // float x = (document.right() + document.left())/2;
            float x = (document.right()-150f);
            float y = 20f;
            pdfContentByte.setTextMatrix(x, y);
            pdfContentByte.showText(text);
            pdfContentByte.endText();

            // 将模板加入到内容（content）中- // 定位'Y'
            pdfContentByte.addTemplate(total, x + textSize, y);

            pdfContentByte.restoreState();
        }

        /**
         * 重写PdfPageEventHelper中的onCloseDocument方法
         */
       /* @Override
        public void onCloseDocument(PdfWriter writer, Document document) {
            total.beginText();
            try {
                String prefixFont = "";
                String os = System.getProperties().getProperty("os.name");
                if(os.startsWith("win") || os.startsWith("Win")){
                    prefixFont = "C:\\Windows\\Fonts" + File.separator;
                }else {
                    prefixFont = "/usr/share/fonts/chinese" + File.separator;
                }

                bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                total.setFontAndSize(bfChinese, 15);
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            total.setTextMatrix(0, 0);
            // 设置总页数的值到模板上，并应用到每个界面
            total.showText(String.valueOf(writer.getPageNumber() - 1));
            total.endText();
        }*/
    }

    public static void main(String[] args) {
        JSONArray array = new JSONArray();
        JSONObject wi = new JSONObject();
        List<JSONObject> list = getBaseJsonData(7);
        wi.put("list",list);
        wi.put("scheduleName","第1周课表");
        wi.put("name","2020年度下学期课表");
        wi.put("typeName","张三");
        array.add(wi);
        JSONObject wi1 = new JSONObject();
        List<JSONObject> list2 = getBaseJsonData(7);
        wi1.put("list",list2);
        wi1.put("scheduleName","第2周课表");
        wi1.put("name","2020年度下学期课表");
        wi1.put("typeName","张三");
        array.add(wi1);
        createCourseSchedulePdf(array,"F:\\aaa");
    }

    public static List<JSONObject> getBaseJsonData(int nodes) {
        List<JSONObject> datas = new ArrayList<>();
        for (int i = 1; i <= nodes; i++) {
            JSONObject j0 = new JSONObject();
            j0.put("section", i);
            for (int k = 1; k < 8; k++) {
                j0.put("w" + k, "");
            }
            datas.add(j0);
        }
        return datas;
    }
}
